const path = require("path");
const glob = require("glob");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const PurgecssPlugin = require("purgecss-webpack-plugin");

module.exports = function (env, argv) {
  const { mode } = argv;

  console.log(env, argv);
  return {
    mode,
    // devtool: "source-map",
    entry: getEntry(),
    output: {
      path: path.resolve(__dirname, "lib"),
      filename: "[name].js",
      library: "uiTest",
      libraryTarget: "umd",
      // umdNamedDefine: true, // umd define name 使用 library 即 uiTest，否则匿名
      globalObject: "this",
    },
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              cacheDirectory: true,
            },
          },
        },
        {
          test: /\.css$/,
          use: [
            MiniCssExtractPlugin.loader,
            {
              loader: "css-loader",
              options: {
                importLoaders: 1, // css-loader前有多少loader
                modules: {
                  auto: true, // eg: *.module.css
                  // localIdentName: "[path][name]__[local]--[hash:base64:5]",
                  localIdentName: "ui_[name]__[local]___[hash:base64:5]",
                  localIdentContext: path.resolve(__dirname, "src/components"),
                },
              },
            },
            {
              loader: "postcss-loader",
              options: {
                postcssOptions: {
                  plugins: [
                    "tailwindcss",
                    "postcss-flexbugs-fixes",
                    [
                      "postcss-preset-env",
                      {
                        autoprefixer: {
                          flexbox: "no-2009",
                        },
                        // features: {
                        //   "nesting-rules": true, // 使用的postcss-nesting，不如postcss-nested好用
                        // },
                        stage: 3,
                        browsers: "defaults, ie 10",
                      },
                    ],
                    "postcss-nested",
                  ],
                },
              },
            },
          ],
        },
        {
          test: /\.(png|jpe?g|gif|svg)$/,
          exclude: path.resolve(__dirname, "src/components/icon/svg"),
          type: "asset",
          parser: {
            dataUrlCondition: {
              maxSize: 10 * 1024, // 10kb, default 8kb
            },
          },
        },
        {
          test: /\.svg$/,
          include: path.resolve(__dirname, "src/components/icon/svg"),
          use: [
            {
              loader: "svg-sprite-loader",
              options: {
                symbolId: "icon-svg-[name]",
              },
            },
            {
              loader: "svgo-loader",
              options: {
                plugins: [
                  {
                    removeAttrs: {
                      // https://github.com/svg/svgo/issues/440
                      // https://github.com/svg/svgo/blob/master/plugins/removeAttrs.js
                      // format: [ element* : attribute* : value* ]
                      // remove attribute (stroke|fill) != none
                      attrs: "*:(stroke|fill):((?!^none$).)*",
                    },
                  },
                ],
              },
            },
          ],
        },
      ],
    },
    externals: {
      react: {
        root: "React",
        commonjs2: "react",
        commonjs: "react",
        amd: "react",
      },
      "prop-types": {
        root: "PropTypes",
        commonjs2: "prop-types",
        commonjs: "prop-types",
        amd: "prop-types",
      },
      classnames: "classNames",
    },
    plugins: [
      new CleanWebpackPlugin({
        cleanAfterEveryBuildPatterns: ["lib"],
      }),
      new MiniCssExtractPlugin({
        filename: "[name].css",
      }),
      new PurgecssPlugin({
        paths: glob.sync(`${path.join(__dirname, "src")}/**/*`, {
          nodir: true,
        }),
      }),
    ],
  };
};

function getEntry() {
  const files = glob
    .sync(path.join(__dirname, "src/**/index.js"))
    .reduce((result, file) => {
      const key = file.replace(/.*?components\/(.*?)\.js/, "$1");

      result[key] = file;
      return result;
    }, {});

  console.log(files);

  return files;
}

// webpack 5+
// 使用，不适合library
// <script src="./runtime.js"></script>
// <script src="./vendors.js"></script>
// <script src="./index.js"></script>
function getEntry5() {
  const files = glob.sync(path.join(__dirname, "src/**/index.js")).reduce(
    (result, file) => {
      const key = file.replace(/.*?components\/(.*?)\.js/, "$1");

      result[key] = {
        import: file,
        dependOn: "vendors",
      };
      return result;
    },
    {
      vendors: {
        import: ["react", "prop-types"],
        runtime: "runtime",
      },
    }
  );

  console.log(files);

  return files;
}
